#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time: 2023/11/22 11:19
# @Author: Anthony (anthony66888@163.com)
# @description: 
"""
import time
from urllib import parse

import requests

from auto_battle_room import YamlControl


class UpdatePrice:
    def __init__(self):
        """初始化登陆后台"""
        self.config_data = YamlControl("/data/config.yaml").read_yaml()
        self.host = self.config_data["admin_host"]  # 生产环境
        self.token = self.config_data["admin_token"]  # 后台token
        self.post_headers = {
            "Token": self.token,
            "Currentroleid": "undefined",
            "Content-Type": "application/x-www-form-urlencoded"
        }
        self.get_headers = {
            "Token": self.token,
            "Currentroleid": "undefined"
        }

    def full_update_lowest_price_and_amount(self, now_time):
        """全量更新平台底价和数量"""
        url = "/api/sys/item/item/synGiftItemInfo"
        data = {
            "appId": 730
        }
        data = parse.urlencode(data)
        try:
            response = requests.post(url=self.host + url, data=data, headers=self.post_headers)
            if response.json()["status"] == 0:
                time.sleep(2)
                update_status = self.get_full_update_lowest_price_and_amount_status(now_time)
                if update_status is not False:
                    while True:
                        update_status = self.get_full_update_lowest_price_and_amount_status(now_time)
                        # if update_status is not False:
                        if update_status["percentage"] == 1:
                            print(f"{now_time} 全量更新平台底价和数量成功")
                            break
                        else:
                            print(f"{now_time} 全量平台底价和数量更新中... 进度为: ", update_status["percentage"])
                            time.sleep(5)
                    return True
            else:
                print(f"{now_time} 全量更新平台底价和数量失败: ", response.json()["msg"])
                return False
        except Exception as e:
            print(f"{now_time} 全量更新平台底价和数量失败", e)
            return False

    def get_full_update_lowest_price_and_amount_status(self, now_time):
        url = "/api/sys/item/item/getSynGiftItemTaskProgressInfo"
        data = {
            "appId": 730
        }
        try:
            response = requests.get(url=self.host + url, params=data, headers=self.get_headers)
            if response.json()["status"] == 0 and response.json()["data"]["total"] > 0:
                return response.json()["data"]
            elif response.json()["data"]["total"] == 0:
                print(f"{now_time} 全量更新平台底价和数量状态失败")
                return False
            else:
                print(f"{now_time} 全量更新平台底价和数量状态失败")
                return False
        except Exception as e:
            print(f"{now_time} 全量更新平台底价和数量状态失败", e)
            return False

    def full_update_recycle_price(self, now_time):
        """全量更新回收价格"""
        url = "/api/sys/priceRule/updatePrice"
        data = {
            "ruleType": -1,
            "ids": ""
        }
        data = parse.urlencode(data)
        try:
            response = requests.post(url=self.host + url, data=data, headers=self.post_headers)
            if response.json()["status"] == 0:
                # print(f"{now_time} 全量更新回收价格成功")
                print(f"{now_time}开始更新回收和阈值价格，过程300s")
                return response.json()
                # return True
            else:
                print(f"{now_time} 全量更新回收价格失败")
                return False
        except Exception as e:
            print(f"{now_time} 全量更新回收价格失败", e)
            return False

    def full_update_mall_price(self, now_time):
        """全量更新出售价格"""
        url = "/api/sys/priceRule/updatePrice"
        data = {
            "ruleType": 3,
            "ids": ""
        }
        data = parse.urlencode(data)
        try:
            response = requests.post(url=self.host + url, data=data, headers=self.post_headers)
            if response.json()["status"] == 0:
                print(f"{now_time} 开始全量更新商城价格，过程需要90s")
                return response.json()
                # return True
            else:
                print(f"{now_time} 全量更新商城价格失败")
                return False
        except Exception as e:
            print(f"{now_time} 全量更新商城价格失败", e)
            return False

    def update_box_price(self, now_time):
        """更新宝箱价格"""
        url = "/api/sys/box/updateBoxPriceOrRate"
        try:
            response = requests.post(url=self.host + url, headers=self.post_headers)
            if response.json()["status"] == 0:
                print(f"{now_time} 更新宝箱价格成功")
                return True
            else:
                print(f"{now_time} 更新宝箱价格失败")
                return False
        except Exception as e:
            print(f"{now_time} 更新宝箱价格失败", e)
            return False


def main():
    now_time = time.strftime("%H:%M:%S", time.localtime())
    # if "15:00:00" < now_time < "18:00:00":
    #     print("当前时间为: ", now_time, "因uu自己价格变动，不执行更新价格操作")
    # else:
    #     update_price = UpdatePrice()
    #     lowest_price_res = update_price.full_update_lowest_price_and_amount(now_time)
    #     time.sleep(5)
    #     if lowest_price_res:
    #         recycle_res = update_price.full_update_recycle_price(now_time)
    #         if recycle_res:
    #             time.sleep(290)
    #             for i in range(1, 11):
    #                 print(f"更新回收和阈值价格等待时间还剩 {11 - i} s...")
    #                 time.sleep(1)
    #             mall_res = update_price.full_update_mall_price(now_time)
    #             if mall_res:
    #                 time.sleep(80)
    #                 for i in range(1, 11):
    #                     print(f"更新商城价格等待时间还剩 {11 - i} s...")
    #                     time.sleep(1)
    #                 update_price.update_box_price(now_time)
    update_price = UpdatePrice()
    lowest_price_res = update_price.full_update_lowest_price_and_amount(now_time)
    time.sleep(5)
    if lowest_price_res:
        recycle_res = update_price.full_update_recycle_price(now_time)
        if recycle_res:
            time.sleep(290)
            for i in range(1, 11):
                print(f"更新回收和阈值价格等待时间还剩 {11 - i} s...")
                time.sleep(1)
            mall_res = update_price.full_update_mall_price(now_time)
            if mall_res:
                time.sleep(80)
                for i in range(1, 11):
                    print(f"更新商城价格等待时间还剩 {11 - i} s...")
                    time.sleep(1)
                update_price.update_box_price(now_time)

if __name__ == '__main__':
    main()
